package com.wenkang.stu.service;

import com.wenkang.stu.enums.ExceptionEnums;
import com.wenkang.stu.exception.KangException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class UploadService {
    private List<String> ALLOW_TYPES = Arrays.asList("image/jpeg", "image/png", "image/bmp", "image/jpg");

    public String uploadImage(MultipartFile file) {
        try {
            // 校验文件类型
            String contentType = file.getContentType();
            if (!ALLOW_TYPES.contains(contentType)) {
                throw new KangException(ExceptionEnums.INVALID_FILE_TYPE);
            }
            // 校验文件内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                throw new KangException(ExceptionEnums.INVALID_FILE_TYPE);
            }
            // 文件重命名
            String imageName = System.currentTimeMillis() + file.getOriginalFilename();
            // 准备目标路径
            File dest = new File("C:\\Users\\99155\\Pictures", imageName);
            // 保存文件到本地
            file.transferTo(dest);
            return "image/" + imageName;
        } catch (Exception e) {
            // 上传失败
            log.error("上传文件失败！", e);
            throw new KangException(ExceptionEnums.UPLOAD_IMAGE_ERROR);
        }
    }
}
